package warbots.gameplay;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;

import warbots.entities.units.Unit;
import warbots.gameplay.exceptions.GameplayException;

/**
 * @author Ido Adler.
 */
public class GamePlay
{
    private Player player2, player1;
    private Queue<Player> players;
    private Map map;
    
    public GamePlay(final Map map, final Player player1, final Player player2)
    {
        this.player1 = player1;
        this.player2 = player2;
        this.map = map;
        
        players = new LinkedList<Player>();
        players.add(this.player1);
        players.add(this.player2);
        
    }
    
	public void init() throws GameplayException {
		for (Player player:players)
		{
			Unit unit = player.chooseUnit();
			map.place(unit);
		}
	}

    public Player gameLoop()
    {
    	// build whatever there is to build before the game begins
    	map.init();
    	
    	Player current = players.poll();
    	while (current.isAlive()){
    		map.initRound();
    		
    		current.turn(map);
    		players.add(current);
    		current = players.poll();
    	}
        
    	return players.poll();
    }
    
    
    /**
     * TODO: description
     * 
     * @param string
     */
    public static String read(final String string)
    {
        
        // prompt the user
        System.out.print(string);
        
        // open up standard input
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        String answer = null;
        
        // read the answer from the command-line
        try
        {
            answer = br.readLine();
        } catch (IOException ioe)
        {
            System.out.println("IO error trying to read");
            System.exit(1);
        }
        return answer;
    }

}
